<!--created by yuyupeng-->
<!--2023/04/13-->
<!-- 令牌管理-->
<template>
  <div class="list-card-container">
    <a-card title="令牌管理" class="general-card">
      <!-- 查询表单 -->
      <AdvancedSearch
        ref="searchRef"
        :data-source="searchItemList"
        @change="searchByParams"
      />
      <a-space style="margin-top: 5px; margin-bottom: 5px">
        <AdvancedDrawer
          click="button"
          title="新增令牌信息"
          clickword="新增令牌"
          :rules="advancedDrawerRules"
          :data-source="addDrawerConfig"
          @change="addDrawerSubmit"
        />
      </a-space>
      <!-- 表格 -->
      <a-table
        v-model:selectedKeys="selectedKeys"
        row-key="client_id"
        column-resizable
        :columns="tbCols"
        :data="tbData"
        :row-selection="rowSelection"
        :pagination="pagination"
        :loading="tbLoading"
        :scroll="{ x: '100%', y: 600 }"
        :scrollbar="true"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 插槽-令牌详情 -->
        <template #detail="{ record }">
          <a-link type="text" @click="showDetailDrawer(record)"> 详情 </a-link>
        </template>
        <!-- 插槽-一键复制 -->
        <template #quickCopyToolTip="{ record, column }">
          <quick-copy-tool-tip
            :show-text="record[column['dataIndex']]"
            show-btn
          />
        </template>
        <!-- 插槽-接入资源列表 -->
        <template #resource_ids="{ record }">
          <span v-if="record.resource_ids">{{
            record.resource_ids.toString()
          }}</span>
        </template>
        <!-- 插槽-权限标识 -->
        <template #authorities="{ record }">
          <span v-if="record.authorities">{{
            record.authorities.toString()
          }}</span>
        </template>
        <!-- 插槽-操作 -->
        <template #operation="{ record }">
          <a-space>
            <a-link type="text" @click="showEditDrawer(record)"> 修改 </a-link>
            <a-link type="text" @click="showUpdateClientSecretDrawer(record)">
              更新密钥
            </a-link>
            <a-popconfirm
              content="确定重置吗?"
              type="warning"
              @ok="submitResetClientSecret(record.client_id)"
            >
              <a-link type="text"> 重置密钥 </a-link>
            </a-popconfirm>
            <a-popconfirm
              content="确定删除吗?"
              type="warning"
              @ok="deleteTbData(record.client_id)"
            >
              <a-link type="text">删除</a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 令牌详情 -->
    <AdvancedShower
      ref="showDrawerRef"
      click="link"
      title="令牌详情"
      clickword=""
      :data-source="sysOauthClientDrawerConfig"
      :data-record="currentRecord"
    />
    <!-- 修改抽屉 -->
    <AdvancedDrawer
      ref="editDrawerRef"
      click="link"
      title="修改令牌信息"
      clickword=""
      :rules="advancedDrawerRules"
      :data-source="editDrawerConfig"
      :data-record="currentRecord"
      @change="editDrawerSubmit"
    />
    <!-- 修改密钥抽屉 -->
    <AdvancedDrawer
      ref="updateClientSecretDrawerRef"
      click="link"
      title="修改令牌密钥"
      clickword=""
      :narrow="true"
      :rules="updateClientSecretDrawerRules"
      :data-source="updateClientSecretDrawerConfig"
      :data-record="currentRecord"
      @change="updateClientSecretDrawerSubmit"
    />
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import {
    Notification,
    TableColumnData,
    TableRowSelection,
  } from '@arco-design/web-vue';
  import {
    querySysOauthClientRecordList,
    addSysOauthClientRecord,
    editSysOauthClientRecord,
    deleteSysOauthClientRecord,
    updateClientSecret,
    resetClientSecret,
  } from '@/api/system/sysOauthClient';
  import { ref, onMounted, reactive, nextTick } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import AdvancedShower from '@/common/components/cac-components/advanced-shower/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';
  import { SysOauthClientRecord } from '@/api/system/model/sysOauthClientModel';

  /**
   * data
   */
  // 表格
  const tbData = ref<SysOauthClientRecord[]>([]);
  const tbCols: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    {
      title: '查看',
      fixed: 'left',
      align: 'center',
      width: 100,
      slotName: 'detail',
    },
    {
      title: '客户端ID',
      width: 150,
      dataIndex: 'client_id',
      fixed: 'left',
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '接入资源列表',
      dataIndex: 'resource_ids',
      width: 150,
      align: 'center',
      tooltip: true,
      slotName: 'resource_ids',
    },
    {
      title: '客户端密钥',
      dataIndex: 'client_secret',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '授权范围',
      dataIndex: 'scope',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '授权类型',
      dataIndex: 'authorized_grant_types',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '回调地址',
      dataIndex: 'redirect_uri',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '权限标识',
      dataIndex: 'authorities',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'authorities',
    },
    {
      title: '访问令牌有效期',
      dataIndex: 'access_token_validity',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '刷新令牌有效期',
      dataIndex: 'refresh_token_validity',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '附加信息',
      dataIndex: 'additional_information',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    /* { title: '', dataIndex: 'createTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '', dataIndex: 'archived', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '', dataIndex: 'trusted', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    {
      title: '自动授权',
      dataIndex: 'autoapprove',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 300,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const showDrawerRef = ref<any>();
  const editDrawerRef = ref<any>();
  const updateClientSecretDrawerRef = ref<any>();
  const currentRecord = ref<SysOauthClientRecord>(); // 记录当前选择的表格行
  const tbLoading = ref<boolean>(false);
  // 勾选框
  const selectedKeys = ref([]);
  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    { type: 'text', labelText: '客户端ID', fieldName: 'client_id' },
    /* { type: 'text', labelText: '接入资源列表', fieldName: 'resource_ids' },
    { type: 'text', labelText: '客户端密钥', fieldName: 'client_secret' },
    { type: 'text', labelText: '授权范围', fieldName: 'scope' },
    {
      type: 'text',
      labelText: '授权类型',
      fieldName: 'authorized_grant_types',
    },
    {
      type: 'text',
      labelText: '回调地址',
      fieldName: 'redirect_uri',
    },
    { type: 'text', labelText: '权限标识', fieldName: 'authorities' },
    {
      type: 'number',
      labelText: '访问令牌有效期',
      fieldName: 'access_token_validity',
    },
    {
      type: 'number',
      labelText: '刷新令牌有效期',
      fieldName: 'refresh_token_validity',
    },
    {
      type: 'text',
      labelText: '附加信息',
      fieldName: 'additional_information',
    }, */
    /* { type: 'text', labelText: '', fieldName: 'createTime'},
    { type: 'text', labelText: '', fieldName: 'archived'},
    { type: 'text', labelText: '', fieldName: 'trusted'},
    { type: 'text', labelText: '自动授权', fieldName: 'autoapprove' }, */
  ];
  // 新增抽屉配置项
  const addDrawerConfig = [
    { type: 'text', labelText: '客户端ID', fieldName: 'client_id' },
    { type: 'text', labelText: '接入资源列表', fieldName: 'resource_ids' },
    { type: 'text', labelText: '客户端密钥', fieldName: 'client_secret' },
    { type: 'text', labelText: '授权范围', fieldName: 'scope' },
    {
      type: 'dictionary',
      labelText: '授权类型',
      fieldName: 'authorized_grant_types',
      dictType: 'authorizationType',
      mode: 'multiple',
    },
    {
      type: 'text',
      labelText: '回调地址',
      fieldName: 'redirect_uri',
    },
    { type: 'text', labelText: '权限标识', fieldName: 'authorities' },
    {
      type: 'number',
      labelText: '访问令牌有效期',
      fieldName: 'access_token_validity',
    },
    {
      type: 'number',
      labelText: '刷新令牌有效期',
      fieldName: 'refresh_token_validity',
    },
    {
      type: 'text',
      labelText: '附加信息',
      fieldName: 'additional_information',
    },
    /* { type: 'text', labelText: '', fieldName: 'createTime'},
    { type: 'text', labelText: '', fieldName: 'archived'},
    { type: 'text', labelText: '', fieldName: 'trusted'}, */
    {
      type: 'radioGroup',
      labelText: '自动授权',
      fieldName: 'autoapprove',
      options: [
        { label: '是', value: 'true' },
        { label: '否', value: 'false' },
      ],
    },
  ];
  // 修改抽屉配置项
  const editDrawerConfig = [
    {
      type: 'text',
      labelText: '客户端ID',
      fieldName: 'client_id',
      disabled: true,
    },
    { type: 'text', labelText: '接入资源列表', fieldName: 'resource_ids' },
    {
      type: 'text',
      labelText: '客户端密钥',
      fieldName: 'client_secret',
      disabled: true,
    },
    { type: 'text', labelText: '授权范围', fieldName: 'scope' },
    {
      type: 'dictionary',
      labelText: '授权类型',
      fieldName: 'authorized_grant_types',
      dictType: 'authorizationType',
      mode: 'multiple',
    },
    {
      type: 'text',
      labelText: '回调地址',
      fieldName: 'redirect_uri',
    },
    { type: 'text', labelText: '权限标识', fieldName: 'authorities' },
    {
      type: 'number',
      labelText: '访问令牌有效期',
      fieldName: 'access_token_validity',
    },
    {
      type: 'number',
      labelText: '刷新令牌有效期',
      fieldName: 'refresh_token_validity',
    },
    {
      type: 'text',
      labelText: '附加信息',
      fieldName: 'additional_information',
    },
    /* { type: 'text', labelText: '', fieldName: 'createTime'},
     { type: 'text', labelText: '', fieldName: 'archived'},
     { type: 'text', labelText: '', fieldName: 'trusted'}, */
    {
      type: 'radioGroup',
      labelText: '自动授权',
      fieldName: 'autoapprove',
      options: [
        { label: '是', value: 'true' },
        { label: '否', value: 'false' },
      ],
    },
  ];
  // 修改密钥抽屉配置项
  const updateClientSecretDrawerConfig = [
    {
      col: 24,
      type: 'text',
      labelText: '客户端ID',
      fieldName: 'clientId',
      disabled: true,
    },
    {
      col: 24,
      type: 'text',
      labelText: '原密钥明文',
      fieldName: 'originClientSecret',
    },
    {
      col: 24,
      type: 'text',
      labelText: '新密钥明文',
      fieldName: 'newClientSecret',
    },
  ];
  // 抽屉表单项校验配置
  const advancedDrawerRules = ref({
    client_id: [{ required: true, message: '请输入客户端ID' }],
    client_secret: [{ required: true, message: '请输入客户端密钥' }],
    scope: [{ required: true, message: '请输入授权范围' }],
    authorized_grant_types: [{ required: true, message: '请输入授权类型' }],
  });
  // 修改密钥抽屉表单项校验配置
  const updateClientSecretDrawerRules = ref({
    originClientSecret: [{ required: true, message: '请输入原密钥明文' }],
    newClientSecret: [{ required: true, message: '请输入新密钥明文' }],
  });
  // 令牌详情抽屉配置项
  const sysOauthClientDrawerConfig = [
    { type: 'text', labelText: '客户端ID', fieldName: 'client_id' },
    { type: 'text', labelText: '接入资源列表', fieldName: 'resource_ids' },
    { type: 'text', labelText: '客户端密钥', fieldName: 'client_secret' },
    { type: 'text', labelText: '授权范围', fieldName: 'scope' },
    {
      type: 'dictionary',
      labelText: '授权类型',
      fieldName: 'authorized_grant_types',
      dictType: 'authorizationType',
      mode: 'multiple',
    },
    {
      type: 'text',
      labelText: '回调地址',
      fieldName: 'redirect_uri',
    },
    { type: 'text', labelText: '权限标识', fieldName: 'authorities' },
    {
      type: 'number',
      labelText: '访问令牌有效期',
      fieldName: 'access_token_validity',
    },
    {
      type: 'number',
      labelText: '刷新令牌有效期',
      fieldName: 'refresh_token_validity',
    },
    {
      type: 'text',
      labelText: '附加信息',
      fieldName: 'additional_information',
    },
    /* { type: 'text', labelText: '', fieldName: 'createTime'},
    { type: 'text', labelText: '', fieldName: 'archived'},
    { type: 'text', labelText: '', fieldName: 'trusted'}, */
    {
      type: 'radioGroup',
      labelText: '自动授权',
      fieldName: 'autoapprove',
      options: [
        { label: '是', value: 'true' },
        { label: '否', value: 'false' },
      ],
    },
  ];
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbData = async (clientId = '') => {
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await querySysOauthClientRecordList(clientId);
      tbData.value = clientId.length > 0 ? [data] : data;
      pagination.total = Number(data.length); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    const clientId = reqdata.client_id ? reqdata.client_id : '';
    if (clientId.replaceAll(' ', '').length > 0) {
      getTbData(clientId);
    } else {
      getTbData();
    }
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    console.log(pageSize);
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 新增抽屉提交
   */
  const addDrawerSubmit = async (reqdata: any) => {
    try {
      const res = (await addSysOauthClientRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 修改抽屉提交
   */
  const editDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await editSysOauthClientRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 修改密钥抽屉提交
   * @param reqdata
   */
  const updateClientSecretDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await updateClientSecret(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 删除令牌信息
   */
  const deleteTbData = async (id: string) => {
    try {
      const res = (await deleteSysOauthClientRecord(id)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 打开详情抽屉
   * @param record 当前选择的表格行数据
   */
  const showDetailDrawer = (record: SysOauthClientRecord) => {
    currentRecord.value = { ...record };
    // 接口给我们的自动授权属性是['false']，我们只需要'false'即可，否则渲染不出来
    if (currentRecord.value.autoapprove) {
      const autoapproveTemp =
        currentRecord.value.autoapprove.length > 0
          ? currentRecord.value.autoapprove[0]
          : 'false';
      currentRecord.value.autoapprove = autoapproveTemp;
    }
    showDrawerRef.value.showDrawer(); // 打开详情抽屉
  };
  /**
   * @description 打开修改抽屉
   * @param record 当前选择的表格行数据
   */
  const showEditDrawer = (record: SysOauthClientRecord) => {
    currentRecord.value = { ...record };
    // 接口给我们的自动授权属性是['false']，我们只需要'false'即可，否则渲染不出来
    if (currentRecord.value.autoapprove) {
      const autoapproveTemp =
        currentRecord.value.autoapprove.length > 0
          ? currentRecord.value.autoapprove[0]
          : 'false';
      currentRecord.value.autoapprove = autoapproveTemp;
    }
    editDrawerRef.value.showDrawer(); // 打开修改抽屉
  };
  /**
   * @description 打开修改密钥抽屉
   * @param record
   */
  const showUpdateClientSecretDrawer = (record: SysOauthClientRecord) => {
    currentRecord.value = { ...record };
    updateClientSecretDrawerRef.value.showDrawer(); // 打开修改密钥抽屉
    nextTick(() => {
      updateClientSecretDrawerRef.value.setFormValues({
        clientId: currentRecord.value?.client_id,
      });
    });
  };
  const submitResetClientSecret = async (clientId: string) => {
    try {
      const res = (await resetClientSecret(clientId)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '密钥明文成功重置为Lcyxxhb.123 请及时修改！',
        });
      } else {
        Notification.error({
          title: '重置失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbData();
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
